import {
	loginMobile,
	getUser
} from 'api/user'

import {
	Toast
} from 'vant'

import {
	getToken,
	setToken,
	removeToken
} from '@/utils/auth'


const LOGIN = 'LOGIN' // 获取用户信息
const SetUserData = 'SetUserData' // 设置用户信息
const LOGOUT = 'LOGOUT' // 退出登录、清除用户数据
const USER_DATA = 'userDate' // 用户数据

export default {
	namespaced: true,
	state: {
		token: getToken() || '',
		user: JSON.parse(localStorage.getItem(USER_DATA) || null)
	},
	mutations: {

		[LOGIN](state, data) {
			let userToken = data.data.token
			state.token = userToken
			setToken(userToken)
		},

		[SetUserData](state, userData = {}) {
			state.user = userData
			localStorage.setItem(USER_DATA, JSON.stringify(userData))
		},
		[LOGOUT](state) {
			state.user = null
			state.token = null
			removeToken()
			localStorage.removeItem(USER_DATA)
		}
	},
	actions: {

		//登录处理 start
		async login(state, data) {
			try {
				let res = await loginMobile(data);
				if(res.code!=200){
					Toast(res.message)
					return
				};
				state.commit(LOGIN, res.data);
				Toast({
					message: '登录成功',
					position: 'middle',
					duration: 1500
				})
				setTimeout(() => {
					data.router.replace(data.toPath)
				}, 1500)
			} catch (error) {}
		},
		//登录处理 end
		
		
		// 获取用户信息  start
		getInfo({
			commit,
			state
		}) {
			return new Promise((resolve, reject) => {
				getUser({
					token: state.token
				}).then(res => {
					
					const {data,message}=res;
					// console.log("读取用户信息：",data)
					if (!data) {
						Toast({
							message: message,
							position: 'middle',
							duration: 4000
						})
						reject('Verification failed, please Login again.');
						return
					}
					commit(SetUserData, data.data)
					resolve(data.data)
				}).catch(error => {
					reject(error)
				})
			})
		}
		// 获取用户信息  end
	},
	getters: {
		token(state) {
			return state.token
		},
		user(state) {
			return state.user
		}
	}
}
